package com.google.project.client.Admin;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import com.google.gwt.cell.client.CheckboxCell;
import com.google.gwt.cell.client.ClickableTextCell;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.SimplePager;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasAlignment;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.DefaultSelectionEventManager;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.MultiSelectionModel;
import com.google.project.client.Service.ProjectService;
import com.google.project.client.Service.ProjectServiceAsync;
import com.google.project.shared.CommonFuntion;
import com.google.project.shared.ProjectDTO;

public class ADMProjectList extends Composite {

	private static final Binder binder = GWT.create(Binder.class);
	@UiField Button btnCreateProject;
	@UiField(provided = true) CellTable<ProjectDTO> ctbProjectList = new CellTable<ProjectDTO>();
	@UiField ListBox cboStatus;
	@UiField TextBox txtProjectName;
	@UiField Button searchBtn;
	@UiField SimplePager pager;
	@UiField Button btnDelete;
	@UiField TextBox txtProjectCode;
	final MultiSelectionModel<ProjectDTO> selectionModel = new MultiSelectionModel<ProjectDTO>();
	private final ProjectServiceAsync projectService = GWT.create(ProjectService.class);
	private List<ProjectDTO> listProjectDTO = new ArrayList<ProjectDTO>();
	private List<ProjectDTO> listProject = new ArrayList<ProjectDTO>();	//Dung de tim kiem theo status (Duoc goi tu Trang Thong tin tong hop)
	private int pjStatus;

	interface Binder extends UiBinder<Widget, ADMProjectList> {
	}

	public ADMProjectList() {
		initWidget(binder.createAndBindUi(this));
		Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() {
			public void execute() {
				txtProjectCode.setFocus(true);
			}
		});
		fillCbStatus();
		initTable();
		bindData();
	}

	public ADMProjectList(int status) {
		this.pjStatus = status;
		initWidget(binder.createAndBindUi(this));
		Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() {
			public void execute() {
				txtProjectCode.setFocus(true);
			}
		});
		fillCbStatus(pjStatus);
		initTable();
		searchFunction(pjStatus);
	}

	/**
	 * Fix data to cboStatus
	 */
	public void fillCbStatus() {
		cboStatus.addItem("---Tất cả---", "-1");
		cboStatus.addItem("Dự án mới", "0");
		cboStatus.addItem("Đang tiến hành", "1");
		cboStatus.addItem("Đã kết thúc", "2");
		cboStatus.setSelectedIndex(-1);
	}

	public void fillCbStatus(int status) {
		cboStatus.addItem("---Tất cả---", "-1");
		cboStatus.addItem("Dự án mới", "0");
		cboStatus.addItem("Đang tiến hành", "1");
		cboStatus.addItem("Đã kết thúc", "2");
		int index = 0;
		if(status == 0) {
			index = 1;
		} else if(status == 1) {
			index = 2;
		} else if(status == 2) {
			index = 3;
		}
		cboStatus.setSelectedIndex(index);
	}
	/**
	 * fill data to ctbProjectList
	 */
	public void bindData() {

		projectService.getProjectList(new AsyncCallback<List<ProjectDTO>>() {

			@Override
			public void onSuccess(List<ProjectDTO> result) {
				listProjectDTO = result;
				loadData(result);
			}

			@Override
			public void onFailure(Throwable caught) {
				Window.alert("Có lỗi trong quá trình Tải thông tin!");
			}
		});
	}

	/**
	 * @param projectList
	 */
	public void loadData(List<ProjectDTO> projectList) {
		// Create a data provider.
		ListDataProvider<ProjectDTO> dataProvider = new ListDataProvider<ProjectDTO>();

		// Add the data to the data provider, which automatically pushes it to
		// the widget

		List<ProjectDTO> list = dataProvider.getList();
		for (int i = 0; i < projectList.size(); i++) {
			projectList.get(i).setIndex(i + 1);
			list.add(projectList.get(i));
		}
		// SimplePager
		pager.setDisplay(ctbProjectList);
		// Connect the table to the data provider.
		dataProvider.addDataDisplay(ctbProjectList);
	}

	// Ham tao Cell table
	public void initTable() {
		// STT
		TextColumn<ProjectDTO> indexColumn = new TextColumn<ProjectDTO>() {
			@Override
			public String getValue(ProjectDTO object) {
				return object.getIndex() + "";
			}
		};

		// Tao checkbox
		ctbProjectList.setSelectionModel(selectionModel, DefaultSelectionEventManager.<ProjectDTO> createCheckboxManager());
		Column<ProjectDTO, Boolean> checkColumn = new Column<ProjectDTO, Boolean>(new CheckboxCell(true, false)) {
			@Override
			public Boolean getValue(ProjectDTO object) {
				// Get the value from the selection model.
				return selectionModel.isSelected(object);
			}
		};

		// Ma du an projectCodeColumn
		Column<ProjectDTO, String> projectCodeColumn = new Column<ProjectDTO, String>(new ClickableTextCell()) {
			@Override
			public String getValue(ProjectDTO object) {
				return object.getProjectCode();
			}
		};
		projectCodeColumn.setFieldUpdater(new FieldUpdater<ProjectDTO, String>() {
			@Override
			public void update(int index, ProjectDTO project,String value) {
				ADMEntrypoint.get().ADMEditProject(project.getProjectID());
			}
		});

		TextColumn<ProjectDTO> projectNameColumn = new TextColumn<ProjectDTO>() {
			@Override
			public String getValue(ProjectDTO object) {
				return object.getProjectName();
			}
		};

		TextColumn<ProjectDTO> pmColumn = new TextColumn<ProjectDTO>() {
			@Override
			public String getValue(ProjectDTO project) {
				return project.getAccountName();
			}
		};
		TextColumn<ProjectDTO> startDateColumn = new TextColumn<ProjectDTO>() {
			@Override
			public String getValue(ProjectDTO project) {
				return CommonFuntion.convertToDate(new Date(project.getStartDate()));
			}
		};
		TextColumn<ProjectDTO> dueDateColumn = new TextColumn<ProjectDTO>() {
			@Override
			public String getValue(ProjectDTO project) {
				return CommonFuntion.convertToDate(new Date(project.getDueDate()));
			}
		};

		TextColumn<ProjectDTO> statusColumn = new TextColumn<ProjectDTO>() {
			@Override
			public String getValue(ProjectDTO project) {
				int status = project.getStatus();
				String _status = "";
				if (status == 0) {
					_status += "Dự án mới";
				} else if (status == 1) {
					_status += "Đang tiến hành";
				} else if (status == 2) {
					_status += "Đã kết thúc";
				}
				return _status;
			}
		};
		ctbProjectList.setWidth("100%", true);
		ctbProjectList.setPageSize(5);
		ctbProjectList.setPageStart(0);
		ctbProjectList.setStyleName("ttable");

		ctbProjectList.addColumn(indexColumn, "STT");
		ctbProjectList.setColumnWidth(indexColumn, 40.0, Unit.PX);

		ctbProjectList.addColumn(checkColumn, SafeHtmlUtils.fromSafeConstant("<br/>"));
		ctbProjectList.setColumnWidth(checkColumn, 40, Unit.PX);

		ctbProjectList.addColumn(projectCodeColumn, "Mã dự án");
		projectCodeColumn.setCellStyleNames("celltable");
		ctbProjectList.setColumnWidth(projectCodeColumn, 15.0, Unit.PCT);

		ctbProjectList.addColumn(projectNameColumn, "Tên dự án");
		ctbProjectList.setColumnWidth(projectNameColumn, 25.0, Unit.PCT);
		projectNameColumn.setHorizontalAlignment(HasAlignment.ALIGN_LEFT);

		ctbProjectList.addColumn(pmColumn, "Quản trị dự án");
		ctbProjectList.setColumnWidth(pmColumn, 20.0, Unit.PCT);

		ctbProjectList.addColumn(startDateColumn, "Ngày bắt đầu");
		ctbProjectList.setColumnWidth(startDateColumn, 20.0, Unit.PCT);
		ctbProjectList.getColumn(ctbProjectList.getColumnIndex(startDateColumn)).setHorizontalAlignment(HasAlignment.ALIGN_CENTER);

		ctbProjectList.addColumn(dueDateColumn, "Ngày kết thúc");
		ctbProjectList.setColumnWidth(dueDateColumn, 20.0, Unit.PCT);
		ctbProjectList.getColumn(ctbProjectList.getColumnIndex(dueDateColumn)).setHorizontalAlignment(HasAlignment.ALIGN_CENTER);

		ctbProjectList.addColumn(statusColumn, "Trạng thái");
		ctbProjectList.setColumnWidth(statusColumn, 15.0, Unit.PCT);
		ctbProjectList.getColumn(ctbProjectList.getColumnIndex(statusColumn)).setHorizontalAlignment(HasAlignment.ALIGN_CENTER);
	}

	/*
	 * Click button "tim kiem"
	 */
	@UiHandler("searchBtn")
	void onSearchBtnClick(ClickEvent event) {
		searchFunction();
	}

	// Ham search
	private void searchFunction() {
		String projectCode = txtProjectCode.getText().trim();
		String projectName = txtProjectName.getText().trim();
		int projectStatus = -2;
		if (cboStatus.getValue(cboStatus.getSelectedIndex()) != null) {
			projectStatus = Integer.parseInt(cboStatus.getValue(cboStatus.getSelectedIndex()));
		}
		Boolean condition = true;

		List<ProjectDTO> temple = new ArrayList<ProjectDTO>();
		for (ProjectDTO project : listProjectDTO) {
			if (projectCode != null) {
				condition = condition && (project.getProjectCode().contains(projectCode));
			}
			if (projectName != null) {
				condition = condition && (project.getProjectName().contains(projectName));
			}
			if ((cboStatus.getValue(cboStatus.getSelectedIndex()) != null) && (!cboStatus.getValue(cboStatus.getSelectedIndex()).equalsIgnoreCase("-1"))) {
				condition = condition && (project.getStatus() == projectStatus);
			}
			if (condition) {
				temple.add(project);
			}
			condition = true;
		}
		if (temple != null) {
			loadData(temple);
		} else {
			loadData(temple);
		}
	}

	private void searchFunction(final int status) {
		projectService.getProjectList(new AsyncCallback<List<ProjectDTO>>() {

			@Override
			public void onSuccess(List<ProjectDTO> result) {
				listProjectDTO = result;
				for(ProjectDTO pj : result) {
					if(pj.getStatus() == status) {
						listProject.add(pj);
					}
				}
				loadData(listProject);
			}

			@Override
			public void onFailure(Throwable caught) {
				Window.alert("Có lỗi trong quá trình Tải thông tin!");
			}
		});
	}
	
	@UiHandler("btnDelete")
	void onBtnDeleteClick(ClickEvent event) {
		Set<ProjectDTO> listChecked = selectionModel.getSelectedSet();
		if (listChecked.isEmpty()) {
			Window.alert("Bạn chưa chọn để xóa!");
		} else {
			int flag = 0;
			List<ProjectDTO> list = new ArrayList<ProjectDTO>();
			for (ProjectDTO project : listChecked) {
				if (project.getStatus() != 0) {
					flag++;
				}else{
					list.add(project);
				}
			}
			if(flag == 0){
				if (Window.confirm("Bạn có chắc chắn muốn xóa?")) {
					projectService.deleteProjectList(list,new AsyncCallback<Void>() {

						@Override
						public void onFailure(Throwable caught) {
							Window.alert("Có lỗi trong quá trình Xóa!");
						}

						@Override
						public void onSuccess(Void result) {
							projectService.getProjectList(new AsyncCallback<List<ProjectDTO>>() {
										
								@Override
								public void onSuccess(List<ProjectDTO> result) {
									listProjectDTO = result;
									searchFunction();
								}
											
								@Override
								public void onFailure(Throwable caught) {
								}
							});
						}
					});
				}
			}else if(flag > 0){
				Window.alert("Không đươc xóa dự án đang triển khai hoặc đã kết thúc!");
			}
		}
		selectionModel.clear();
	}

	@UiHandler("btnCreateProject")
	void onBtnCreateProjectClick(ClickEvent event) {
		ADMEntrypoint.get().ADMCreateProjectList();
	}
}
